home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / textwrap.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  12KB  |  319 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Text wrapping and filling.
  5. '''
  6. __revision__ = '$Id: textwrap.py 68135 2009-01-01 15:46:10Z georg.brandl $'
  7. import string
  8. import re
  9. __all__ = [
  10.     'TextWrapper',
  11.     'wrap',
  12.     'fill',
  13.     'dedent']
  14. _whitespace = '\t\n\x0b\x0c\r '
  15.  
  16. class TextWrapper:
  17.     '''
  18.     Object for wrapping/filling text.  The public interface consists of
  19.     the wrap() and fill() methods; the other methods are just there for
  20.     subclasses to override in order to tweak the default behaviour.
  21.     If you want to completely replace the main wrapping algorithm,
  22.     you\'ll probably have to override _wrap_chunks().
  23.  
  24.     Several instance attributes control various aspects of wrapping:
  25.       width (default: 70)
  26.         the maximum width of wrapped lines (unless break_long_words
  27.         is false)
  28.       initial_indent (default: "")
  29.         string that will be prepended to the first line of wrapped
  30.         output.  Counts towards the line\'s width.
  31.       subsequent_indent (default: "")
  32.         string that will be prepended to all lines save the first
  33.         of wrapped output; also counts towards each line\'s width.
  34.       expand_tabs (default: true)
  35.         Expand tabs in input text to spaces before further processing.
  36.         Each tab will become 1 .. 8 spaces, depending on its position in
  37.         its line.  If false, each tab is treated as a single character.
  38.       replace_whitespace (default: true)
  39.         Replace all whitespace characters in the input text by spaces
  40.         after tab expansion.  Note that if expand_tabs is false and
  41.         replace_whitespace is true, every tab will be converted to a
  42.         single space!
  43.       fix_sentence_endings (default: false)
  44.         Ensure that sentence-ending punctuation is always followed
  45.         by two spaces.  Off by default because the algorithm is
  46.         (unavoidably) imperfect.
  47.       break_long_words (default: true)
  48.         Break words longer than \'width\'.  If false, those words will not
  49.         be broken, and some lines might be longer than \'width\'.
  50.       break_on_hyphens (default: true)
  51.         Allow breaking hyphenated words. If true, wrapping will occur
  52.         preferably on whitespaces and right after hyphens part of
  53.         compound words.
  54.       drop_whitespace (default: true)
  55.         Drop leading and trailing whitespace from lines.
  56.     '''
  57.     whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace))
  58.     unicode_whitespace_trans = { }
  59.     uspace = ord(u' ')
  60.     for x in map(ord, _whitespace):
  61.         unicode_whitespace_trans[x] = uspace
  62.     
  63.     wordsep_re = re.compile('(\\s+|[^\\s\\w]*\\w+[^0-9\\W]-(?=\\w+[^0-9\\W])|(?<=[\\w\\!\\"\\\'\\&\\.\\,\\?])-{2,}(?=\\w))')
  64.     wordsep_simple_re = re.compile('(\\s+)')
  65.     sentence_end_re = re.compile('[%s][\\.\\!\\?][\\"\\\']?\\Z' % string.lowercase)
  66.     
  67.     def __init__(self, width = 70, initial_indent = '', subsequent_indent = '', expand_tabs = True, replace_whitespace = True, fix_sentence_endings = False, break_long_words = True, drop_whitespace = True, break_on_hyphens = True):
  68.         self.width = width
  69.         self.initial_indent = initial_indent
  70.         self.subsequent_indent = subsequent_indent
  71.         self.expand_tabs = expand_tabs
  72.         self.replace_whitespace = replace_whitespace
  73.         self.fix_sentence_endings = fix_sentence_endings
  74.         self.break_long_words = break_long_words
  75.         self.drop_whitespace = drop_whitespace
  76.         self.break_on_hyphens = break_on_hyphens
  77.         self.wordsep_re_uni = re.compile(self.wordsep_re.pattern, re.U)
  78.         self.wordsep_simple_re_uni = re.compile(self.wordsep_simple_re.pattern, re.U)
  79.  
  80.     
  81.     def _munge_whitespace(self, text):
  82.         '''_munge_whitespace(text : string) -> string
  83.  
  84.         Munge whitespace in text: expand tabs and convert all other
  85.         whitespace characters to spaces.  Eg. " foo\tbar
  86.  
  87. baz"
  88.         becomes " foo    bar  baz".
  89.         '''
  90.         if self.expand_tabs:
  91.             text = text.expandtabs()
  92.         
  93.         if self.replace_whitespace:
  94.             if isinstance(text, str):
  95.                 text = text.translate(self.whitespace_trans)
  96.             elif isinstance(text, unicode):
  97.                 text = text.translate(self.unicode_whitespace_trans)
  98.             
  99.         
  100.         return text
  101.  
  102.     
  103.     def _split(self, text):
  104.         """_split(text : string) -> [string]
  105.  
  106.         Split the text to wrap into indivisible chunks.  Chunks are
  107.         not quite the same as words; see wrap_chunks() for full
  108.         details.  As an example, the text
  109.           Look, goof-ball -- use the -b option!
  110.         breaks into the following chunks:
  111.           'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
  112.           'use', ' ', 'the', ' ', '-b', ' ', 'option!'
  113.         if break_on_hyphens is True, or in:
  114.           'Look,', ' ', 'goof-ball', ' ', '--', ' ',
  115.           'use', ' ', 'the', ' ', '-b', ' ', option!'
  116.         otherwise.
  117.         """
  118.         if isinstance(text, unicode):
  119.             if self.break_on_hyphens:
  120.                 pat = self.wordsep_re_uni
  121.             else:
  122.                 pat = self.wordsep_simple_re_uni
  123.         elif self.break_on_hyphens:
  124.             pat = self.wordsep_re
  125.         else:
  126.             pat = self.wordsep_simple_re
  127.         chunks = pat.split(text)
  128.         chunks = filter(None, chunks)
  129.         return chunks
  130.  
  131.     
  132.     def _fix_sentence_endings(self, chunks):
  133.         '''_fix_sentence_endings(chunks : [string])
  134.  
  135.         Correct for sentence endings buried in \'chunks\'.  Eg. when the
  136.         original text contains "... foo.
  137. Bar ...", munge_whitespace()
  138.         and split() will convert that to [..., "foo.", " ", "Bar", ...]
  139.         which has one too few spaces; this method simply changes the one
  140.         space to two.
  141.         '''
  142.         i = 0
  143.         pat = self.sentence_end_re
  144.         while i < len(chunks) - 1:
  145.             if chunks[i + 1] == ' ' and pat.search(chunks[i]):
  146.                 chunks[i + 1] = '  '
  147.                 i += 2
  148.                 continue
  149.             i += 1
  150.  
  151.     
  152.     def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
  153.         '''_handle_long_word(chunks : [string],
  154.                              cur_line : [string],
  155.                              cur_len : int, width : int)
  156.  
  157.         Handle a chunk of text (most likely a word, not whitespace) that
  158.         is too long to fit in any line.
  159.         '''
  160.         if width < 1:
  161.             space_left = 1
  162.         else:
  163.             space_left = width - cur_len
  164.         if self.break_long_words:
  165.             cur_line.append(reversed_chunks[-1][:space_left])
  166.             reversed_chunks[-1] = reversed_chunks[-1][space_left:]
  167.         elif not cur_line:
  168.             cur_line.append(reversed_chunks.pop())
  169.         
  170.  
  171.     
  172.     def _wrap_chunks(self, chunks):
  173.         '''_wrap_chunks(chunks : [string]) -> [string]
  174.  
  175.         Wrap a sequence of text chunks and return a list of lines of
  176.         length \'self.width\' or less.  (If \'break_long_words\' is false,
  177.         some lines may be longer than this.)  Chunks correspond roughly
  178.         to words and the whitespace between them: each chunk is
  179.         indivisible (modulo \'break_long_words\'), but a line break can
  180.         come between any two chunks.  Chunks should not have internal
  181.         whitespace; ie. a chunk is either all whitespace or a "word".
  182.         Whitespace chunks will be removed from the beginning and end of
  183.         lines, but apart from that whitespace is preserved.
  184.         '''
  185.         lines = []
  186.         if self.width <= 0:
  187.             raise ValueError('invalid width %r (must be > 0)' % self.width)
  188.         self.width <= 0
  189.         chunks.reverse()
  190.         while chunks:
  191.             cur_line = []
  192.             cur_len = 0
  193.             if lines:
  194.                 indent = self.subsequent_indent
  195.             else:
  196.                 indent = self.initial_indent
  197.             width = self.width - len(indent)
  198.             if self.drop_whitespace and chunks[-1].strip() == '' and lines:
  199.                 del chunks[-1]
  200.             
  201.             while chunks:
  202.                 l = len(chunks[-1])
  203.                 if cur_len + l <= width:
  204.                     cur_line.append(chunks.pop())
  205.                     cur_len += l
  206.                     continue
  207.                 break
  208.             if chunks and len(chunks[-1]) > width:
  209.                 self._handle_long_word(chunks, cur_line, cur_len, width)
  210.             
  211.             if self.drop_whitespace and cur_line and cur_line[-1].strip() == '':
  212.                 del cur_line[-1]
  213.             
  214.             if cur_line:
  215.                 lines.append(indent + ''.join(cur_line))
  216.                 continue
  217.         return lines
  218.  
  219.     
  220.     def wrap(self, text):
  221.         """wrap(text : string) -> [string]
  222.  
  223.         Reformat the single paragraph in 'text' so it fits in lines of
  224.         no more than 'self.width' columns, and return a list of wrapped
  225.         lines.  Tabs in 'text' are expanded with string.expandtabs(),
  226.         and all other whitespace characters (including newline) are
  227.         converted to space.
  228.         """
  229.         text = self._munge_whitespace(text)
  230.         chunks = self._split(text)
  231.         if self.fix_sentence_endings:
  232.             self._fix_sentence_endings(chunks)
  233.         
  234.         return self._wrap_chunks(chunks)
  235.  
  236.     
  237.     def fill(self, text):
  238.         """fill(text : string) -> string
  239.  
  240.         Reformat the single paragraph in 'text' to fit in lines of no
  241.         more than 'self.width' columns, and return a new string
  242.         containing the entire wrapped paragraph.
  243.         """
  244.         return '\n'.join(self.wrap(text))
  245.  
  246.  
  247.  
  248. def wrap(text, width = 70, **kwargs):
  249.     """Wrap a single paragraph of text, returning a list of wrapped lines.
  250.  
  251.     Reformat the single paragraph in 'text' so it fits in lines of no
  252.     more than 'width' columns, and return a list of wrapped lines.  By
  253.     default, tabs in 'text' are expanded with string.expandtabs(), and
  254.     all other whitespace characters (including newline) are converted to
  255.     space.  See TextWrapper class for available keyword args to customize
  256.     wrapping behaviour.
  257.     """
  258.     w = TextWrapper(width = width, **kwargs)
  259.     return w.wrap(text)
  260.  
  261.  
  262. def fill(text, width = 70, **kwargs):
  263.     """Fill a single paragraph of text, returning a new string.
  264.  
  265.     Reformat the single paragraph in 'text' to fit in lines of no more
  266.     than 'width' columns, and return a new string containing the entire
  267.     wrapped paragraph.  As with wrap(), tabs are expanded and other
  268.     whitespace characters converted to space.  See TextWrapper class for
  269.     available keyword args to customize wrapping behaviour.
  270.     """
  271.     w = TextWrapper(width = width, **kwargs)
  272.     return w.fill(text)
  273.  
  274. _whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE)
  275. _leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE)
  276.  
  277. def dedent(text):
  278.     '''Remove any common leading whitespace from every line in `text`.
  279.  
  280.     This can be used to make triple-quoted strings line up with the left
  281.     edge of the display, while still presenting them in the source code
  282.     in indented form.
  283.  
  284.     Note that tabs and spaces are both treated as whitespace, but they
  285.     are not equal: the lines "  hello" and "\thello" are
  286.     considered to have no common leading whitespace.  (This behaviour is
  287.     new in Python 2.5; older versions of this module incorrectly
  288.     expanded tabs before searching for common leading whitespace.)
  289.     '''
  290.     margin = None
  291.     text = _whitespace_only_re.sub('', text)
  292.     indents = _leading_whitespace_re.findall(text)
  293.     for indent in indents:
  294.         if margin is None:
  295.             margin = indent
  296.             continue
  297.         if indent.startswith(margin):
  298.             continue
  299.         if margin.startswith(indent):
  300.             margin = indent
  301.             continue
  302.         margin = ''
  303.         break
  304.     
  305.     if 0 and margin:
  306.         for line in text.split('\n'):
  307.             if not not line and line.startswith(margin):
  308.                 raise AssertionError, 'line = %r, margin = %r' % (line, margin)
  309.         
  310.     
  311.     if margin:
  312.         text = re.sub('(?m)^' + margin, '', text)
  313.     
  314.     return text
  315.  
  316. if __name__ == '__main__':
  317.     print dedent('Hello there.\n  This is indented.')
  318.  
  319.